var express = require('express');
var base_router = express.Router();
var db = require('../models')
var path = require('path')
var fs = require('fs')
var comm = require('../comm')
const cfg = require('../config')
const RQ = require('request-promise')
const stringRandom = require('string-random');
const crypto = require('crypto')

base_router.get('/homeRecommendation', async (req, res) => {
  //db.topic.sync({alter: true})
  var [page = 1, pagesize = 12,order='ASC',orderBy='sort'] = [req.body.pageNo, req.body.pageSize,req.body.order,req.body.orderBy]
  let condition = {
    "pagesize": pagesize,
    "page": page,
    'order':order,
    'orderBy':orderBy
  }  
  let list = await db.topic.getHomeRecommendation(condition)
  res.json(list);
});

base_router.get('/getBannerList', async (req, res) =>{
  let list = await db.banner.getBannerList({status:0})
  res.json(list)
} )

base_router.get('/get-shot', async (req, res) => {
	let imgname = req.query.img
	if( imgname == undefined || imgname == '' ){
		return res.sendFile('static/images/404.jpg')
	}
	try{
		if (process.env.NODE_ENV === "production") {
			let spn = imgname.split('/')
			if (spn[spn.length - 1].startsWith('thumbnail.') || spn[spn.length - 1].startsWith('v_')) {
				let p = path.resolve("/static/gallery/" + imgname, "./")
				if (!fs.existsSync(p)) {
					let dirs = path.dirname(p)
					//下载到本地
					comm.mkdirsSync(dirs)
					let result = await comm.oss.get(imgname, p)
					if (result.res.status !== 200) {
						return res.send('error')
					}
				}
				res.sendFile(p)
			} else {
				comm.oss.getStream(imgname).then((result) => {
					res.set('Content-Type', result.stream.headers['content-type'])
					result.stream.pipe(res)
				}).catch(e => {
					console.log(e)
					res.send('error')
				})
			}
		} else {
			let p = path.resolve("static/gallery/" + imgname, "./")
			if (!fs.existsSync(p)) {
				let dirs = path.dirname(p)

				//下载到本地
				comm.mkdirsSync(dirs)
				let result = await comm.oss.get(imgname, p)
				if (result.res.status !== 200) {
					return res.send('error')
				}
			}
			res.sendFile(p)
			//res.send(p)
		}
	}catch (err){
		console.log(err)
		res.send('error')
	}
})

base_router.get('/get_image', async (req, res) => {
	let imgname = req.query.img
	try{
		if (process.env.NODE_ENV === "production") {
			let spn = imgname.split('/')
			if (spn[spn.length - 1].startsWith('thumbnail.') || spn[spn.length - 1].startsWith('v_')) {
				let p = path.resolve("/static/images/" + imgname, "./")
				if (!fs.existsSync(p)) {
					let dirs = path.dirname(p)
					//下载到本地
					comm.mkdirsSync(dirs)
					let result = await comm.oss.get(imgname, p)
					if (result.res.status !== 200) {
						return res.send('error')
					}
				}
				res.sendFile(p)
			} else {
				comm.oss.getStream(imgname).then((result) => {
					res.set('Content-Type', result.stream.headers['content-type'])
					result.stream.pipe(res)
				}).catch(e => {
					console.log(e)
					res.send('error')
				})
			}
		} else {
			let p = path.resolve("static/images/" + imgname, "./")
			if (!fs.existsSync(p)) {
				let dirs = path.dirname(p)
				//下载到本地
				comm.mkdirsSync(dirs)
				let result = await comm.oss.get(imgname, p)
				if (result.res.status !== 200) {
					return res.send('error')
				}
			}
			res.sendFile(p)
			//res.send(p)
		}
	}catch (err){
		console.log(err)
		res.send('error')
	}
})

//发送短信
base_router.post('/sendcode', async (req, res) => {
	const url = 'https://open.ucpaas.com/ol/sms/sendsms';
	let result = {"code":500, "msg":"error"}
	let sessionkey = req.cookies['connect.sid']
	sessionkey = crypto.createHash('md5').update(sessionkey).digest("hex")

	let key = await comm.redget(sessionkey);
	if( key != null ){
			result.msg = 'sd'
			return res.json(result)
	}

	if( req.body.tonum == undefined || req.body.tonum == ''){
			result.code  = 400
			return res.json(result)
	}

	let verifycode = stringRandom(6, { letters: false })
	comm.redis.set(sessionkey, `${verifycode}|${req.body.tonum}`);
	comm.redis.expire(sessionkey, 180)

	let yzxresponse = await RQ({uri: url, method: 'POST', json: true,
			rejectUnauthorized:false,
			headers: { "Content-Type": "application/json;charset=utf-8", "content-type": "application/json" },
			body: {
					sid: cfg.yunzhixui.sid, 
					token: cfg.yunzhixui.token, 
					appid: cfg.yunzhixui.appid, 
					templateid: cfg.yunzhixui.templateid, 
					mobile: req.body.tonum, 
					param: `${verifycode},3`,
					uid: ''
			}
	}).then(res=>{
			return res
	}).catch(err=>{
			console.log('send code error!!', err)
			return 'fail'
	})

	if (yzxresponse.code == '000000') {
			result.code = 200
			result.msg = "ok"
			result.id = yzxresponse.smsid
	}

	return res.json(result)
})


module.exports = base_router